<template>
    <div class="app-container">
      <!-- 搜索区域保持不变 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <!-- 原有搜索表单 -->
        <el-form-item label="源模型名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入源模型名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="源模型类别" prop="category">
        <el-input v-model="queryParams.category" placeholder="请输入源模型类别" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-form>
  
      <!-- 操作按钮区域保持不变 -->
      <el-row :gutter="10" class="mb8">
        <!-- 原有操作按钮 -->
        <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['smodel:smodel:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['smodel:smodel:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['smodel:smodel:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          v-hasPermi="['smodel:smodel:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <!-- 表格区域保持不变 -->
      <el-table v-loading="loading" :data="smodelList" @selection-change="handleSelectionChange">
        <!-- 原有表格列 -->
        <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="源模型ID" align="center" prop="id" />
      <el-table-column label="源模型名称" align="center" prop="name" />
      <el-table-column label="源模型类别" align="center" prop="category" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"></el-table-column>
        <el-table-column label="模型文件" align="center" prop="modelFile" width="200">
          <template slot-scope="scope">
            <el-button link type="primary" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['smodel:smodel:edit']">修改</el-button>
          <el-button link type="primary" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['smodel:smodel:remove']">删除</el-button>
            <el-button v-if="scope.row.modelFile" size="mini" type="text" @click="downloadFile(scope.row.modelFile)">下载</el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件保持不变 -->
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList" />
  
      <!-- 添加/修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="smodelRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="源模型名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入源模型名称" />
          </el-form-item>
          
          <el-form-item label="源模型文件" prop="modelFile">
            <el-upload
              class="upload-demo"
              action=""
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :file-list="fileList"
              :limit="1"
            >
              <el-button size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传.py文件，且不超过500MB</div>
            </el-upload>
          </el-form-item>
          
          <el-form-item label="源模型类别" prop="category">
            <el-input v-model="form.category" placeholder="请输入源模型类别" />
          </el-form-item>
        </el-form>
        <template slot="footer">
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listSmodel, getSmodel, delSmodel, addSmodel, updateSmodel } from "@/api/smodel/smodel";
  import { uploadFile } from "@/api/common";
  
  export default {
    name: "Smodel",
    data() {
      return {
        // 原有数据属性
        // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 源模型表格数据
      smodelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        modelFile: null,
        category: null,
      },
      // 表单参数
      form: {},
        fileList: [], // 上传文件列表
        uploadFile: null, // 当前上传的文件对象
        
        // 表单校验增加文件校验
        rules: {
          name: [{ required: true, message: "源模型名称不能为空", trigger: "blur" }],
          category: [{ required: true, message: "源模型类别不能为空", trigger: "blur" }],
          modelFile: [{ required: true, message: "请上传模型文件", trigger: "blur" }]
        }
      };
    },
    created() {
    this.getList();
  },
    methods: {
         /** 查询源模型列表 */
    getList() {
      this.loading = true;
      listSmodel(this.queryParams).then(response => {
        this.smodelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
     /** 搜索按钮操作 */
     handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加源模型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSmodel(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改源模型";
      });
    },
      // 文件状态改变时的钩子
      handleFileChange(file, fileList) {
        this.uploadFile = file.raw;
        this.form.modelFile = file.name;
        this.fileList = fileList.slice(-1); // 只保留最新文件
      },
      
      // 上传前校验
      beforeUpload(file) {
        const isPython = file.name.endsWith('.py');
        const isLt500M = file.size / 1024 / 1024 < 500;
        
        if (!isPython) {
          this.$message.error('只能上传Python文件(.py)');
        }
        if (!isLt500M) {
          this.$message.error('文件大小不能超过500MB');
        }
        
        return isPython && isLt500M;
      },
      
      // 下载文件
      downloadFile(filePath) {
        window.open(process.env.VUE_APP_BASE_API + filePath);
      },
      /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除源模型编号为"' + ids + '"的数据项？').then(() => {
        return delSmodel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
     /** 导出按钮操作 */
     handleExport() {
      this.download('smodel/smodel/export', {
        ...this.queryParams
      }, `smodel_${new Date().getTime()}.xlsx`)
    },
      // 修改提交表单方法
      submitForm() {
        this.$refs["smodelRef"].validate(valid => {
          if (valid) {
            if (!this.uploadFile && !this.form.id) {
              this.$message.error('请上传模型文件');
              return;
            }
            
            let formData = new FormData();
            if (this.uploadFile) {
              formData.append('file', this.uploadFile);
            }
            formData.append('name', this.form.name);
            formData.append('category', this.form.category);
            if (this.form.id) {
              formData.append('id', this.form.id);
            }
            
            const apiCall = this.form.id ? updateSmodel : addSmodel;
            apiCall(formData).then(response => {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            });
          }
        });
      },
      
      // 修改重置方法
      reset() {
        this.form = {
          id: null,
          name: null,
          modelFile: null,
          category: null
        };
        this.fileList = [];
        this.uploadFile = null;
        this.resetForm("smodelRef");
      },
      
      // 原有其他方法保持不变
    }
  };
  </script>